package com.huatech.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 管理平台公共业务封装
 * 
 * @author lh
 */
@Controller
public class BaseController {


	public final static String SUCCESS = "success";
	public final static String ERROR = "errorMsg";//PC系统错误页面
	public final static String APP_ERROR = "app/msg_fail";//app系统错误页面
	public final static String FAIL = "fail";
	public final static String OK = "ok";
	public final static String MSG = "msg";
    
	protected ServletContext context;

	protected List<String> names = null;

	/**
	 * 
	 * @Title: getRequest @Description: 当前的请求对象 @return
	 *         HttpServletRequest @throws
	 */
	protected HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
	}

	protected HttpSession getSession() {
		return getRequest().getSession();
	}

	protected void printWebSuccess(HttpServletResponse response) throws IOException {
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("result", true);
		printWebJson(data, response);
	}

	protected void printWebResult(String msg, boolean result, HttpServletResponse response) throws IOException {
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("msg", msg);
		data.put("result", result);
		printWebJson(data, response);
	}

	protected void printWebJson(Object json, HttpServletResponse response) throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(json);
		out.flush();
		out.close();
	}

	protected void printWebFlag(boolean flag, HttpServletResponse response) throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(flag);
		out.flush();
		out.close();
	}

	/**
	 * 回调打印
	 */
	protected void printSuccessReturn(HttpServletResponse response) {
		try {
			response.setContentType("text/html;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			response.getWriter().write("SUCCESS");
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
